package com.ssm.util;

import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Program name: StringUtil
 * Program description: String Util.
 * Author: jack
 * 
 * Revision history:
 * Description of Change	Programmer		Date
 * ---------------------	----------		----
 * Initial creation		    jack	        Apr 5, 2009
 *  
 * Copyright (c) 2009 by zezhong Pte Ltd
 * ALL RIGHTS RESERVED
 */

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


//
//import com.tito.common.t.JsonDateValueProcessor;

public final class StringUtil extends org.apache.commons.lang.StringUtils {

	public static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat sdf_num_only = new SimpleDateFormat(
			"yyyyMMddHHmmss");
	public static SimpleDateFormat sdfShort = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat sdfLong = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat sdfLong2 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");
	public static SimpleDateFormat sdfLong3 = new SimpleDateFormat(
			"yyyy-MM-dd HH");
	public static SimpleDateFormat sdfLong4 = new SimpleDateFormat(
			"yyyy-MM-dd");
	public static SimpleDateFormat sdfLong5 = new SimpleDateFormat(
			"yyyyMMdd-HHmmss");
	public static SimpleDateFormat sdfLong6 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss.SSS");
	public static SimpleDateFormat sdfLong7 = new SimpleDateFormat(
			"HH:mm");
	public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
	public static SimpleDateFormat mdyShort = new SimpleDateFormat("MM/dd/yyyy");
	public static DecimalFormat decfmt = new DecimalFormat("##0.0");
	
	public static SimpleDateFormat simpleDateFormat4log = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSS");
	
	public static char splitflag = 0;
	public static char splitflag1 = 1;
	public static char splitflag2 = 2;
	public static char splitflag3 = 3; // 代替页面显示 #
	public static char splitflag4 = 4; // 代替页面显示 &

	private static Pattern emailPattern = Pattern
			.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");

	private static Pattern phonePattern = Pattern
			.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

	private static Pattern postalCodePattern = Pattern
			.compile("^[1-9][0-9]{5}$");
	private static Pattern telePhonePattern = java.util.regex.Pattern
			.compile("1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}");
	public static String splitStr = "&&";// 用来过滤用例录入换行字符
	public static String strDefaultKey = "zezhongspasvosoft";
	public static String[] keyword = { "ab", "bc", "cd", "de", "ef", "fg",
			"gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr",
			"rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za", "abc2",
			"bcd2", "cde3", "def4", "efg5", "fgh6", "ghi7", "hik8", "ikl9",
			"klm9", "lmn8", "mno7", "nop6", "opq5", "pqr4", "qrs3", "rst2",
			"stu1", "tuv0", "uvx1", "vxy2", "xyz3", "zac4", "zac5", "zac6" };
	
	public static Calendar calendar = Calendar.getInstance();

	public static boolean isNull(String value) {
		if (value == null || "".equals(value.trim()) || "null".equals(value)) {
			return true;
		} else {
			return false;
		}
	}

	public static String fllterStr(Object value) {
		if (value == null) {
			return "";
		}
		return value.toString().replaceAll("'", "").replaceAll("%", "")
				.replaceAll("&", "_").trim();
	}

	public static String fllterStr1(Object value) {
		if (value == null) {
			return "";
		}
		return value.toString().replaceAll("'", "").replace("&", "_").trim();
	}

	public static String fllterStr2(Object value) {
		if (value == null) {
			return "";
		}
		return value.toString().replaceAll("'", "\\'")// .replace("&", "\\&")
				.replace("_", "\\_").replace("%", "\\%").trim();
	}

	/**
	 * 从HTML格式的文本转换成JAVA后台文本(暂时不作修改)
	 * 
	 * @param value
	 * @return
	 */
	public static String html2Text(String value) {
		if (isNull(value)) {
			return "";
		}
		return value
		// .replaceAll("\\n", "")
		// .replaceAll("&apos;", "'")
		// .replaceAll("&quot;", "\"")
		// .replaceAll("&lt;", "<")
		// .replaceAll("&gt;", ">")
		;
	}

	/**
	 * 从JAVA后台文本格式转换成HTML格式文本
	 * 
	 * @param value
	 * @return
	 */
	public static String text2HTML(String value) {
		if (isNull(value)) {
			return "";
		}
		return value
		// .replaceAll("<br />", "\\n")
		// .replaceAll("'", "&apos;")
		// .replaceAll("\"", "&quot;")
		// .replaceAll("<", "&lt;")
		// .replaceAll(">", "&gt;")
		;
	}

	/**
	 * 转换字符串为list
	 * 
	 * @param value
	 * @return
	 */
	public static List<Integer> convertStringToList(String value) {
		String[] idArr = value.split(";");
		List<Integer> ids = new ArrayList<Integer>(idArr.length);
		for (String id : idArr) {
			ids.add(Integer.parseInt(id));
		}
		return ids;
	}

	// public synchronized static String encrypt(String in, int id) {
	// try {
	// if (instance == null)
	// instance = new DemoSecurity(null);
	// int len = keyword.length;
	// int level = id / len % len;
	// int level1 = id % len;
	// instance.setUserKey(keyword[level1] + keyword[level]);
	// return instance.encrypt(in);
	// } catch (Exception e) {
	// e.getMessage();
	// return in;
	// }
	// }

	// public synchronized static String dencrypt(String in, int id) {
	// try {
	// if (instance == null)
	// instance = new DemoSecurity(null);
	// int len = keyword.length;
	// int level = id / len % len;
	// int level1 = id % len;
	// instance.setUserKey(keyword[level1] + keyword[level]);
	// return instance.decrypt(in);
	// } catch (Exception e) {
	// e.getMessage();
	// return in;
	// }
	// }

	/**
	 * 
	 * Method: getNow
	 * <P>
	 * Description: 获取当前时间
	 * <P>
	 * 
	 * @see <br>
	 * @param
	 * @return created by jackee YU 下午01:29:42
	 */
	public static java.sql.Timestamp getNow() {
		java.util.Date utilDate = new Date();
		return new java.sql.Timestamp(utilDate.getTime());
	}

	/**
	 * Date转Timestamp
	 * 
	 * @return
	 */
	public static java.sql.Timestamp getTimestamp(java.util.Date date) {
		try {
			return new java.sql.Timestamp(date.getTime());
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 
	 * Method: getNow
	 * <P>
	 * Description: 获取当前时间
	 * <P>
	 * 
	 * @see <br>
	 * @param
	 * @return created by jackee YU 下午01:29:42
	 */
	public static java.sql.Date getNowDate() {
		java.util.Date utilDate = new Date();
		return new java.sql.Date(utilDate.getTime());
	}

	public static java.sql.Date getNowDate(Date date) {
		return new java.sql.Date(date.getTime());
	}

	public static String now(String format) {
		// SimpleDateFormat f = new SimpleDateFormat(format);
		return sdf.format(new Date());
	}

	public static String getTimeNumber() {
		// SimpleDateFormat f = new SimpleDateFormat(format);
		return sdf_num_only.format(new Date());
	}

	public static Date now() {
		return new Date();
	}

	/**
	 * 获得添加天数后的日期
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	// public static Date getAddDate(Date date) throws ParseException {
	// Calendar cal = Calendar.getInstance();
	// cal.add(Calendar.DATE, pwdAvaliableDays);// 增加的天数
	// cal.set(Calendar.HOUR_OF_DAY, 23);
	// cal.set(Calendar.MINUTE, 59);
	// cal.set(Calendar.SECOND, 59);
	// date = cal.getTime();
	// String backTime = sdf.format(date);
	// return sdf.parse(backTime);
	// }

	/**
	 * 离指定日期还有多少天
	 * 
	 * @param start
	 *            开始日期
	 * @param end
	 *            结束日期
	 * @return
	 * @throws ParseException
	 */
	public static long dateDifferent(Date start, Date end)
			throws ParseException {
		long startTime = start.getTime();
		long endTime = end.getTime();
		long days = Math.abs(endTime - startTime) / (1000 * 60 * 60 * 24);
		if (startTime > endTime) {
			days = -days;
		}
		return days;
	}

	public static String getCurrMonthFirstDay() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Date theDate = calendar.getTime();

		GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
		gcLast.setTime(theDate);
		gcLast.set(Calendar.DAY_OF_MONTH, 1);
		String day_first = df.format(gcLast.getTime());
		StringBuffer str = new StringBuffer().append(day_first).append(
				" 00:00:00");
		return str.toString();

	}

	public static String getCurrMonthLastDay() {
		Calendar c = Calendar.getInstance();
		try {
			c.set(Calendar.DATE, 1);
			c.add(Calendar.MONTH, 1);
			c.add(Calendar.DATE, -1);
			return sdfShort.format(c.getTime()) + " 23:59:59";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 获取当年的第一天
	 * 
	 * @param year
	 * @return
	 */
	public static Date getCurrYearFirst() {
		Calendar currCal = Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return getYearFirst(currentYear);
	}

	/**
	 * 获取当年的第一天
	 * 
	 * @param year
	 * @return
	 */
	public static String getCurrYearFirst2String() {
		Calendar currCal = Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return sdfLong.format(getYearFirst(currentYear));
	}

	/**
	 * 获取当年的最后一天
	 * 
	 * @param year
	 * @return
	 */
	public static String getCurrYearLast2String() {
		Calendar currCal = Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return sdfLong.format(getYearLast(currentYear));
	}

	/**
	 * 获取当年的最后一天
	 * 
	 * @param year
	 * @return
	 */
	public static Date getCurrYearLast() {
		Calendar currCal = Calendar.getInstance();
		int currentYear = currCal.get(Calendar.YEAR);
		return getYearLast(currentYear);
	}

	/**
	 * 获取某年第一天日期
	 * 
	 * @param year
	 *            年份
	 * @return Date
	 */
	public static Date getYearFirst(int year) {
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		Date currYearFirst = calendar.getTime();
		return currYearFirst;
	}

	/**
	 * 获取某年最后一天日期
	 * 
	 * @param year
	 *            年份
	 * @return Date
	 */
	public static Date getYearLast(int year) {
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		calendar.roll(Calendar.DAY_OF_YEAR, -1);
		Date currYearLast = calendar.getTime();

		return currYearLast;
	}

	/**
	 * 获取以传进来时间为标注的昨天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getYesterDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取以传进来时间为标注的的往前day天数
	 * 
	 * @param date
	 * @return
	 */
	public static Date getThePast(Date date, int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1 * day);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取以传进来时间为标注的的往前day天数
	 * 
	 * @param date
	 * @return
	 */
	public static Date getNextYear(Date date, int year) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.YEAR, year);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 获取以传进来时间为标注的的往后day天数
	 * 
	 * @param date
	 * @return
	 */
	public static Date getTheNextDate(Date date, int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, 1 * day);
		date = calendar.getTime();
		return date;
	}

	/**
	 * 当前季度的开始时间，即2012-01-1 00:00:00
	 * 
	 * @return
	 */
	public static String getCurrentQuarterStartTime() {
		Calendar c = Calendar.getInstance();
		int currentMonth = c.get(Calendar.MONTH) + 1;
		try {
			if (currentMonth >= 1 && currentMonth <= 3)
				c.set(Calendar.MONTH, 0);
			else if (currentMonth >= 4 && currentMonth <= 6)
				c.set(Calendar.MONTH, 3);
			else if (currentMonth >= 7 && currentMonth <= 9)
				c.set(Calendar.MONTH, 6);
			else if (currentMonth >= 10 && currentMonth <= 12)
				c.set(Calendar.MONTH, 9);
			c.set(Calendar.DATE, 1);
			return sdfShort.format(c.getTime()) + " 00:00:00";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 当前季度的结束时间，即2012-03-31 23:59:59
	 * 
	 * @return
	 */
	public static String getCurrentQuarterEndTime() {
		Calendar c = Calendar.getInstance();
		int currentMonth = c.get(Calendar.MONTH) + 1;
		try {
			if (currentMonth >= 1 && currentMonth <= 3) {
				c.set(Calendar.MONTH, 2);
				c.set(Calendar.DATE, 31);
			} else if (currentMonth >= 4 && currentMonth <= 6) {
				c.set(Calendar.MONTH, 5);
				c.set(Calendar.DATE, 30);
			} else if (currentMonth >= 7 && currentMonth <= 9) {
				c.set(Calendar.MONTH, 8);
				c.set(Calendar.DATE, 30);
			} else if (currentMonth >= 10 && currentMonth <= 12) {
				c.set(Calendar.MONTH, 11);
				c.set(Calendar.DATE, 31);
			}
			return sdfShort.format(c.getTime()) + " 23:59:59";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date getFormatDate(String date) throws ParseException {
		if (date == null || "".equals(date)) {
			return null;
		}
		return sdf.parse(date);
	}

	public static Date getFormatShortDate(String date) {
		try {
			if (date == null || "".equals(date)) {
				return null;
			}
			return sdfShort.parse(date);
		} catch (Exception e) {
			return null;
		}
	}

	public static Date getFormatLongDate(String date) throws ParseException {
		if (date == null || "".equals(date)) {
			return null;
		}
		return sdfLong.parse(date);
	}

	public static String getFormatShortDate2(Date date) {
		if (date == null)
			return "";
		return sdfLong2.format(date);
	}

	public static java.sql.Timestamp getFormatTimestamp(String date)
			throws ParseException {
		java.util.Date utilDate = sdf.parse(date);
		return new java.sql.Timestamp(utilDate.getTime());
	}

	public static String getNow1() {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date());
	}

	public static String getNowShort() {
		return sdfShort.format(new Date());
	}

	public static String getFormatDate(Date date) {
		if (date == null)
			return "";
		return sdf.format(date);
	}

	public static String getFormatShortDate(Date date) {
		if (date == null)
			return "";
		return sdfShort.format(date);
	}

	public static String getFormatMdyShortDate(Date date) {
		if (date == null)
			return "";
		return mdyShort.format(date);
	}

	public synchronized static Long getTime() {
		Date d = new Date();
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return d.getTime();
	}

	public synchronized static String getUploadFilePah(String path) {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Date d = new Date();
		return path.concat("\\" + d.getTime());
	}

	/**
	 * 使用splitChar 分割字符串
	 * 
	 * @param target
	 * @param splitChar
	 * @return
	 */
	public synchronized static String[] splitString(String target,
			char splitChar) {

		ArrayList<String> moduleValueList = new ArrayList<String>();

		int index = target.indexOf(splitChar);
		while (index >= 0) {
			if (index == 0) {
				moduleValueList.add("");
			} else {
				moduleValueList.add(target.substring(0, index - 1));
			}

			if (index == (target.length() - 1)) {
				break;
			}

			target = target.substring(index + 1);
			index = target.indexOf(splitChar);
		}

		if (index == (target.length() - 1)) {
			moduleValueList.add("");
		} else {
			moduleValueList.add(target);
		}

		return moduleValueList.toArray(new String[] {});
	}

	public static String getFormatReg(String rgStr) {
		String[] str = rgStr.split("");
		StringBuffer newstr = new StringBuffer();
		newstr.append("reg['");
		for (int i = 0; i < str.length; i++) {
			if (str[i].equals("\\")) {
				str[i] = str[i] + str[i];
			}
			newstr.append(str[i]);
		}
		newstr.append("']");
		return newstr.toString();
	}

	/**
	 * 获取模块一正则表达式
	 * 
	 * @param rgStr
	 * @return
	 */
	public static String getFormatModuleReg(String rgStr) {
		String[] str = rgStr.split("");
		StringBuffer newstr = new StringBuffer();
		newstr.append("moduleReg['");
		for (int i = 0; i < str.length; i++) {
			if (str[i].equals("\\")) {
				str[i] = str[i] + str[i];
			}
			newstr.append(str[i]);
		}
		newstr.append("']");
		return newstr.toString();
	}

	@SuppressWarnings("static-access")
	public static java.sql.Date getDelayDate(Integer month) {
		try {
			sdf.parse(getNow1());
			Calendar dateCalendar = sdf.getCalendar();
			dateCalendar.add(dateCalendar.MONTH, month);
			Date d = dateCalendar.getTime();
			return new java.sql.Date(d.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static boolean compareDate(Date date) {
		if (date == null) {
			return true;
		}
		String endDate = sdf.format(date);
		String today = getNowShort();
		if (endDate.compareTo(today) < 1) {
			return false;
		}
		return true;
	}

	public static String getRealAge(Date desc) {
		Calendar now = Calendar.getInstance();
		int monthOfNow = now.get(Calendar.MONTH) + 1;
		int yearOfNow = now.get(Calendar.YEAR);

		Calendar descCal = Calendar.getInstance();
		descCal.setTime(desc);
		int monthOfDesc = descCal.get(Calendar.MONTH) + 1;
		int yearOfDesc = descCal.get(Calendar.YEAR);

		int between = (yearOfNow - yearOfDesc) * 12
				+ (monthOfNow - monthOfDesc);

		return between + "";
	}

	public static boolean testEmail(String s) {
		return emailPattern.matcher(s).matches();
	}

	public static boolean testPhone(String s) {
		return phonePattern.matcher(s).matches();
	}

	public static boolean testTelePhone(String s) {
		return telePhonePattern.matcher(s).matches();
	}

	public static boolean testPostalCode(String s) {
		return postalCodePattern.matcher(s).matches();
	}

	/**
	 * JSON转换 日期为空格式
	 * 
	 * @param data
	 * @return
	 */
//	public static <T> JSONArray getJSONData(List<T> data) {
//		JsonConfig jsonConfig = new JsonConfig();
//		jsonConfig.registerJsonValueProcessor(Date.class,
//				new JsonDateValueProcessor());
//		return JSONArray.fromObject(data, jsonConfig);
//	}

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * JSON转换 日期为空格式
	 * 
	 * @param data
	 * @return
	 */
//	public static <T> JSONObject getJSONData(T data) {
//		JsonConfig jsonConfig = new JsonConfig();
//		jsonConfig.registerJsonValueProcessor(Date.class,
//				new JsonDateValueProcessor());
//		return JSONObject.fromObject(data, jsonConfig);
//	}

	public static Date getFormatDatePlug(String date) throws ParseException {
		if (date == null || "".equals(date)) {
			return null;
		}
		date = date.replace("Z", " UTC");
		date = date.replace("\"", "");
		return format.parse(date);
	}
	
	public static Date getNowDataPreviousHour(){
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - 1);
		return c.getTime();
	}
	public static Date getFormatDate2(String date) throws ParseException {
		if (date == null || "".equals(date)) {
			return null;
		}
		return sdfLong2.parse(date);
	}
	public static Date getFormatDate3(String date) throws ParseException {
		if (date == null || "".equals(date)) {
			return null;
		}
		return sdfLong3.parse(date);
	}
	public static Date getFormatDate4(String date) throws ParseException {
		if (date == null || "".equals(date)) {
			return null;
		}
		return sdfLong4.parse(date);
	}
	public static Date getFormatDate6(String date) throws ParseException {
		if (date == null || "".equals(date)) {
			return null;
		}
		return sdfLong6.parse(date);
	}
	
	public static int getYear(Date date){
		if(date == null || "".equals(date)){
			return 0;
		}
		calendar.setTime(date);
		return calendar.get(Calendar.YEAR);
	}
	
	
	//判断字符串是否是 JSON 格式
	public static boolean isJSON(String str){
		try {
//			JSONObject.fromObject(str);
			JSON.parseObject(str);
			return  true;
		} catch (Exception e) {
			return false;
		}
	}
	
	//字符串转JSON
	public static JSONObject getJSON(String str){
		try {
//			return JSONObject.fromObject(str);
			return JSON.parseObject(str);
		} catch (Exception e) {
			return null;
		}
	}
	//判断字符串是否是 JSONArray 格式
	public static boolean isJSONArray(String str){
		try {
//			JSONObject.fromObject(str);
			JSON.parseArray(str);
			return  true;
		} catch (Exception e) {
			return false;
		}
	}
	//字符串转JSONArray
	public static JSONArray getJSONArray(String str){
		try {
//			return JSONObject.fromObject(str);
			return JSON.parseArray(str);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * public int indexOf(int ch, int fromIndex)
	 * 返回在此字符串中第一次出现指定字符处的索引，从指定的索引开始搜索
	 * 
	 * @param srcText
	 * @param findText
	 * @return
	 */
	public static int appearNumber(String srcText, String findText) {
	    int count = 0;
	    int index = 0;
	    while ((index = srcText.indexOf(findText, index)) != -1) {
	        index = index + findText.length();
	        count++;
	    }
	    return count;
	}
	
	public static String pattern = "yyyyMMdd HH:mm:ss.SSS";
	public static String pattern2 = "[dd/MMM/yyyy:HH:mm:ss Z]";
	private static Map<String,ThreadLocal<SimpleDateFormat>> localMap = 
			new HashMap<String,ThreadLocal<SimpleDateFormat>>();
	public static SimpleDateFormat getSimpleDateFormat(String pattern){
		if(!localMap.containsKey(pattern)){
			SimpleDateFormat sdf = null;
			if(pattern.equals(pattern2)){
				sdf = new SimpleDateFormat(pattern,new Locale("ENGLISH", "CHINA"));
			}else{
				sdf = new SimpleDateFormat(pattern);
			}
			ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>();
			local.set(sdf);
			localMap.put(pattern, local);
		}else{
			SimpleDateFormat sdf = localMap.get(pattern).get();
			if(sdf == null){
				if(pattern.equals(pattern2)){
					sdf = new SimpleDateFormat(pattern,new Locale("ENGLISH", "CHINA"));
				}else{
					sdf = new SimpleDateFormat(pattern);
				}
				localMap.get(pattern).set(sdf);
			}
		}
		return localMap.get(pattern).get();
	}
	
	

    public static String getUTF8StringFromGBKString(String gbkStr) {  
        try {  
            return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");  
        } catch (Exception e) {  
            throw new InternalError();  
        }  
    }  
      
    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {  
        int n = gbkStr.length();  
        byte[] utfBytes = new byte[3 * n];  
        int k = 0;  
        for (int i = 0; i < n; i++) {  
            int m = gbkStr.charAt(i);  
            if (m < 128 && m >= 0) {  
                utfBytes[k++] = (byte) m;  
                continue;  
            }  
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));  
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));  
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));  
        }  
        if (k < utfBytes.length) {  
            byte[] tmp = new byte[k];  
            System.arraycopy(utfBytes, 0, tmp, 0, k);  
            return tmp;  
        }  
        return utfBytes;  
    } 
    public static String getUTFString(String str) {
		String encode = "UTF-8";
		String returnStr = "";
		try {
			if(str!=null){
				if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
				}else if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
					encode = "ISO-8859-1";
				}else if (str.equals(new String(str.getBytes("UTF-8"), "UTF-8"))) {
				}else if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
					encode = "GBK";
				}
				if(encode.equals("UTF-8")){
					returnStr = str;
				}else{
					returnStr = new String(str.getBytes(encode),"UTF-8");
				}
			}
		} catch (Exception ex) {
			returnStr = "乱码";
			ex.printStackTrace();
		}
		return returnStr;
	}
    
    public static Connection getSqlServerConnection(String ip,String user,String password,String database) {
		Connection conn = null;
	
		 String urlSys ="jdbc:sqlserver://"+ip+";DatabaseName="+database;
		 String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(urlSys, user, password);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.print("sqlSever连接失败");
		}
		return conn;
	} 
    
    /**
     * BASE64解码 
     * @param encoder
     * @return
     * @throws Exception
     */
    public static String BASE64Decoder(String encoder,String encoded) throws Exception{
//    	return new String(Base64.getUrlDecoder().decode(encoder),encoded);
//    	return new String(Base64.getMimeDecoder().decode(encoder),encoded);
    	
//    	if(encoder.length() % 4 != 0){
//    		encoder = encoder.substring(0, encoder.length() - encoder.length() % 4);
//    	}
    	return new String(Base64.getDecoder().decode(encoder),encoded);
    }
    /**
     * BASE64编码
     * @param decoder
     * @return
     * @throws Exception
     */
    public static String BASE64Encoder(String decoder,String encoded) throws Exception{
    	return Base64.getEncoder().encodeToString(decoder.getBytes(encoded));
    }
    
    /*
     * 字符是否为中文
     */
    public static boolean isChineseChar(char c){
    	try {
			return String.valueOf(c).getBytes("UTF-8").length > 1;
		} catch (Exception e) {
			return false;
		}
    }
}
